<template>
  <view>
    <SearchTable ref="search" :config="config" :columns="columns"
                 :pagination="pagination" :loadData="loadData"/>
    <EditDialog ref="editDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
  </view>
</template>

<script setup lang="ts" name="platformList">

import {onActivated, reactive, ref, toRaw} from "vue";
import SearchTable from "@/components/common/SearchTable.vue";
import {useStore} from "@/stores";
import router from "@/router";
import EditDialog from "@/components/common/EditDialog.vue";
import {loadPlatformPage, addPlatform, updatePlatform, platformUpdateCache} from "@/apis";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import {View} from "@element-plus/icons-vue";
import {create20, create32} from "@/utils/StrUtil";
import {getStateOptions, getStateTag, getStateText} from "@/utils/SystemUtil";

const search = ref(null);
const editDlg = ref(null);
const currentItem = ref<any>();

const store = useStore()
const emits = defineEmits(['switchToPage']);

const rules = reactive({
  name: [{required: true, message: '请输入平台名称', trigger: ['blur', 'change']},],
})

const loadData = async (params: any) => {
  if (params.applyDate && params.applyDate.length === 2) {
    params.startTime = params.applyDate[0];
    params.endTime = params.applyDate[1];
  }
  const recentPlatforms: any = [];
  const result = await loadPlatformPage(params);
  if (result && result.data && result.data.data) {
    result.data.data.forEach((item: any) => {
      recentPlatforms.push({
        id: item.id,
        label: item.name,
        desc: item.name,
        realmId: item.realmId,
      });
    })
  }

  store.setRecentPlatforms(recentPlatforms);

  return result;
}

const onSubmit = async (item: Record<string, any>, editType: string) => {
  if ("add" == editType) {
    const result = await addPlatform(item);
    if (result.code === 0) {
      msgInfo('新增平台信息成功！');
      search.value?.refresh();
    } else {
      msgError(result.message);
    }

    return result;

  } else {
    const result = await updatePlatform(item);
    if (result.code === 0) {
      msgInfo('保存平台信息成功！');
      search.value?.refresh();
    } else {
      msgError(result.message);
    }

    return result;
  }

}

const newPlatform = () => {
  return {
    state: 1,
    id: create20(),
    secret: create32()
  };
}

const searchItems = [
  {
    type: 'input',
    name: 'name',
    label: '名称',
    size: 'default',
    placeholder: '请输入平台',
    clearable: true,
  },
  {
    type: 'date-range',
    subType: 'datetimerange',
    name: 'applyDate',
    label: '申请时间',
    size: 'default',
    placeholder: '请选择',
    placeholders: [
      '开始时间', '结束时间'
    ],
    clearable: true,
    format: 'YYYY/MM/DD HH:mm:ss',
    valFormat: 'YYYY-MM-DD HH:mm:ss',
  }
]

const tableAction = [
  {
    type: 'primary', name: 'add', label: '新增', icon: 'Plus', action: () => {
      currentItem.value = newPlatform();
      editDlg.value?.editAdd('新增平台', currentItem.value);
    }
  },
]

const pagination = ref<Pagination>({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'name',
    name: '平台名称',
    sort: 'custom',
    show: true,
    action: (data: any, row: any, index: number) => {
      const platform = row;
      emits('switchToPage', platform);
      store.switchToPlatform(toRaw(platform));
      router.push({
        path: '/platform'
      })
    }
  },
  {
    id: 'id',
    name: '平台标识',
    hideCol: true,
    show: true,
    canEdit: true,
    readOnly: true,
  },
  {
    id: 'logo',
    name: '平台LOGO',
    show: false,
  },
  {
    id: 'secret',
    name: '平台秘钥',
    show: false,
    readOnly: true,
    extBtn: {
      name: '重新生成',
      action: (item: any) => {
        item.secret = create32();
      }
    }
  },
  {
    id: 'homeUrl',
    name: '首页地址',
    show: true,
    action: (data: any, row: any, index: number) => {
      if (row.homeUrl) {
        // window.location.href = row.homeUrl;
        window.open(row.homeUrl);
      }
    }
  },
  {
    id: 'ticketUrl',
    name: '验证地址',
    show: true
  },
  {
    id: 'contact',
    name: '联系人',
    show: true,
  },
  {
    id: 'createTime',
    name: '申请时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'realmId',
    name: '所属域',
    show: true,
    readOnly: true,
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => {
      return getStateTag(tag);
    },
    tagText: (tag: number) => {
      return getStateText(tag);
    },
    options: getStateOptions()
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    hideCol: true,
    canEdit: false,
    fixed: 'right',
    operations: [
      {
        name: '编辑',
        callback: (data: any, row: any) => {
          currentItem.value = row;
          editDlg.value?.editUpdate('编辑平台', row);
        }
      },
      {
        type: 'confirm',
        name: '更新缓存',
        tips: () => {
          return '确定更新平台缓存？'
        },
        iconType: 'primary',
        confirm: async (data: any, row: any) => {
          const result: any = await platformUpdateCache({
                id: row.id
              }
          )
          if (result && result.code == 0) {
            msgInfo('操作成功')
          }
        }
      },
    ]
  }
]);

const config = ref<SearchConfig>({
  showSearch: true,
  search: searchItems,
  tableAction: tableAction,
  title: '平台列表',
  toolMode: '',
  setting: {
    showMoreSearch: false,
    showMoreButton: true,
    disableMoreButton: true,
    tableToolRound: '0',
    tableToolBackground: '',
  },
  layout: {
    buttonSize: 'default',
    actionButtonSize: 'default',
    inputSize: 'default',
  },
});

onActivated(() => {
  if (!store.$state.listPage) {
    router.push({
      path: store.$state.platformPath
    })
  }
})

</script>

<style scoped>
</style>
